package ltd.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/*
 * 创建一个session对象
 * 使用的是单例模式
 * Created by chinalin on 2017/4/12.
 *
 * 用spring的context构造，无需cfg.xml配置
 */
@Deprecated
public class HibernateUtil {
    //提供私有的对象
    private static SessionFactory sessionFactory;
    //提供一个私有的构造方法，避免给外界去创建对象
    private HibernateUtil(){}
    public static SessionFactory getSessionFactory(){
        //加载hibernate的总配置文件
        Configuration cfg=new Configuration().configure();
        //注册serviceRegistry对象
//        ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        //解决线程安全问题
        if (sessionFactory==null) {
            //使用同步锁解决多个线程创建对象
            synchronized(HibernateUtil.class){
                //解决：只能创建一次
                if (sessionFactory==null) {
                    sessionFactory=cfg.buildSessionFactory(serviceRegistry);
                }
            }
        }
        return sessionFactory;
    }
}
